package com.sinodata.bsm.cicp.collector.tomcat;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.JmxUtil;
import com.sinodata.bsm.common.vo.ResPropertyValue;

public class ClassLoadCollecotr extends Collector {
    private static Logger logger = Logger.getLogger(ClassLoadCollecotr.class);

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String port = this.getParamMap().get("Port");
        String[] propertyNames = new String[] { "LoadedClassCount", "UnloadedClassCount", "TotalLoadedClassCount" };
        Object[] attrValues = null;

        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];

        JMXConnector connector = null;
        MBeanServerConnection connection = null;
        try {
            //connector = JmxUtil.getConnection(JmxUtil.TOMCAT, ip + ":" + port);
            connector = JmxUtil.getConnection(ip, Integer.parseInt(port));
            connection = connector.getMBeanServerConnection();
            ObjectName classLoading = new ObjectName("java.lang:type=ClassLoading");
            Set<ObjectName> set = connection.queryNames(classLoading, null);
            for (ObjectName objectName : set) {
                attrValues = JmxUtil.getAttribute(connection, objectName, propertyNames);
                for (int i = 0; i < attrValues.length; i++) {
                    propValues[i] = ResPropertyValue.createPropValue(attrValues[i].toString(), propMetas[i]);
                }
            }
        } catch (Exception e) {
            logger.error("when ClassLoadCollecotr" + e);
            throw new CollectorException(e);
        } finally {
            JmxUtil.closeConnector(connector);
        }
        propertyValueX.setValues(propValues);
        values.add(propertyValueX);
        return values;
    }

    @Override
    public String[] getParamMeta() {
        //        return new String[] { "名称", "端口" };
        return new String[] { "Name", "Port" };
    }

    @Override
    public String[] getPropMeta() {
        //        return new String[] { "当前装入类的数量", "已卸载类的数量", "已装入类的总数" };
        return new String[] { "$1", "$2", "$3" };
    }
}
